package com.example.yin.service.impl;

import com.example.yin.dao.ConsumerMapper;
import com.example.yin.dao.MenuMapper;
import com.example.yin.domain.Consumer;
import com.example.yin.domain.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        List<Consumer> users = consumerMapper.selectbyusername(username);
        //如果查询不到数据就通过抛出异常来给出提示
//        if(Objects.isNull(user)){
//            throw new RuntimeException("用户名或密码错误");
//        }
        if(users.isEmpty()){
            throw new RuntimeException(("用户名或密码错误"));
        }
        //根据用户查询权限信息 添加到LoginUser中
        List<String> permissionKeyList =  menuMapper.selectPermsByUserId(users.get(0).getId());
        //List<String> aaa = Arrays.asList(new String[]{"test"});
        System.out.println(permissionKeyList);
        //封装成UserDetails对象返回
        return new LoginUser(users.get(0),permissionKeyList);
    }
}

